package com.sailfish.springbootdemo.service.db2.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB2Config;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db2.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.*;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class PcbCapacityApproveDetailServiceImpl implements PcbCapacityApproveDetailService {

    @Autowired
    PcbCapacityApproveDetailDao pcbCapacityApproveDetailDao;
    @Autowired
    PcbCapacityDataApproveDao pcbCapacityDataApproveDao;
    @Autowired
    PcbApproveProcessDao pcbApproveProcessDao;
    @Autowired
    UserDao userDao;
    @Autowired
    PcbSonFactoryInfoDao pcbSonFactoryInfoDao;
    @Autowired
    PcbCapacityApproveDetailFileDao pcbCapacityApproveDetailFileDao;
    @Autowired
    PcbApproveConfigDao pcbApproveConfigDao;
    @Autowired
    PcbCapacityDataService pcbCapacityDataService;
    @Autowired
    CapacityMatchService capacityMatchService;
    @Autowired
    ThirdApiService thirdApiService;
    @Autowired
    OperateService operateService;
    @Autowired
    S3UploadFileService s3UploadFileService;


    @Value("${personal.config.env}")
    String env;

    @Override
    public List<PcbCapacityApproveDetail> getApproveDetail(Integer id, Integer flowType) {
        List<PcbCapacityApproveDetail> pcbCapacityApproveDetails = pcbCapacityApproveDetailDao.getByLimit(flowType, id);
        for (int i = 0; i < pcbCapacityApproveDetails.size(); i++) {
            PcbCapacityApproveDetail pcbCapacityApproveDetail = pcbCapacityApproveDetails.get(i);
            if (pcbCapacityApproveDetail.getApplyUserId() != null) {
                User userInfoById = userDao.getUserInfoById(pcbCapacityApproveDetail.getApplyUserId());
                pcbCapacityApproveDetail.setApplyUserInfo(userInfoById);
            }
            if (pcbCapacityApproveDetail.getApproveUserId() != null) {
                User userInfoById = userDao.getUserInfoById(pcbCapacityApproveDetail.getApproveUserId());
                pcbCapacityApproveDetail.setApproveUserInfo(userInfoById);
            }
            if (pcbCapacityApproveDetail.getCopyUserId() != null) {
                User userInfoById = userDao.getUserInfoById(pcbCapacityApproveDetail.getCopyUserId());
                pcbCapacityApproveDetail.setCopyUserInfo(userInfoById);
            }
            if (pcbCapacityApproveDetail.getCreateUser() != null) {
                User userInfoById = userDao.getUserInfoById(Integer.parseInt(pcbCapacityApproveDetail.getCreateUser()));
                pcbCapacityApproveDetail.setCreateUserInfo(userInfoById);
            }
            if (pcbCapacityApproveDetail.getUpdateUser() != null) {
                User userInfoById = userDao.getUserInfoById(Integer.parseInt(pcbCapacityApproveDetail.getUpdateUser()));
                pcbCapacityApproveDetail.setUpdateUserInfo(userInfoById);
            }
            if (pcbCapacityApproveDetail.getSonFactoryId() != null) {
                PcbSonFactoryInfo pcbSonFactoryInfo = pcbSonFactoryInfoDao.getById(pcbCapacityApproveDetail.getSonFactoryId());
                pcbCapacityApproveDetail.setSonFactoryInfo(pcbSonFactoryInfo);
            }
            if (pcbCapacityApproveDetail.getNextNodeUserId() != null) {
                User userInfoById = userDao.getUserInfoById(pcbCapacityApproveDetail.getNextNodeUserId());
                pcbCapacityApproveDetail.setNextNodeUserInfo(userInfoById);
            }
            List<PcbCapacityApproveDetailFile> pcbCapacityApproveDetailFileList = pcbCapacityApproveDetailFileDao.getByLimit(pcbCapacityApproveDetail.getFlowType(), pcbCapacityApproveDetail.getId());
            for (int a = 0; a < pcbCapacityApproveDetailFileList.size(); a++) {
                final String url = pcbCapacityApproveDetailFileList.get(a).getUrl();
                if (!StringUtils.isBlank(url)) {
                    String base64Image = s3UploadFileService.getImageBase64FromUrl(url);
                    pcbCapacityApproveDetailFileList.get(a).setImageBase64(CommonUtils.base64Prefix() + base64Image);
                }
            }
            pcbCapacityApproveDetail.setFileList(pcbCapacityApproveDetailFileList);
        }
        return pcbCapacityApproveDetails;
    }

    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result changeApprover(Integer id, Integer approveUserId) {
        try {

            String userId = UserHeaderHolder.getUserId();
            PcbCapacityApproveDetail oldData = pcbCapacityApproveDetailDao.getById(id);

            PcbCapacityDataApprove pcbCapacityDataApprove = pcbCapacityDataApproveDao.getById(oldData.getDataId());
            pcbCapacityDataApprove.setApproveUserId(approveUserId.toString());
            pcbCapacityDataApproveDao.update(pcbCapacityDataApprove);

            PcbCapacityApproveDetail pcbCapacityApproveDetail = new PcbCapacityApproveDetail();
            pcbCapacityApproveDetail.setId(id);
            pcbCapacityApproveDetail.setApproveUserId(approveUserId);
            int count = pcbCapacityApproveDetailDao.update(pcbCapacityApproveDetail);
            if (count > 0) {
                PcbCapacityApproveDetail newData = pcbCapacityApproveDetailDao.getById(id);
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批细节", 2, 1, new Date(), JSONObject.toJSONString(oldData), JSONObject.toJSONString(newData)));
            } else {
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    /*提交下一环节*/
    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result submitToNextNode(String data) {
        String userId = UserHeaderHolder.getUserId();
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer id = jsonObject.getInteger("id");
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "param id is null", null);
        }
        JSONArray fileList = jsonObject.getJSONArray("fileList");
        Integer copyUserId = jsonObject.getInteger("copyUserId");
        Integer nextNodeUserId = jsonObject.getInteger("nextNodeUserId");
        Integer nnextNodeUserId = null;
        String remark = jsonObject.getString("remark");
        PcbCapacityApproveDetail pcbCapacityApproveDetail = pcbCapacityApproveDetailDao.getById(id);
        String str_oldPcbCapacityApproveDetail = JSONObject.toJSONString(pcbCapacityApproveDetail);
        String oldStatus = pcbCapacityApproveDetail.getApproveNode();
        int approveDataId = pcbCapacityApproveDetail.getDataId();
        PcbCapacityDataApprove pcbCapacityDataApprove = pcbCapacityDataApproveDao.getById(approveDataId);
        String str_oldPcbCapacityDataApprove = JSONObject.toJSONString(pcbCapacityDataApprove);
        int flowType = pcbCapacityDataApprove.getFlowType();

        Integer factoryId = pcbCapacityDataApprove.getFactoryId();
        if (factoryId == -1) {
            factoryId = null;
        }
        PcbApproveConfig approveConfig = pcbApproveConfigDao.getOneByLimit(flowType, null, factoryId);

        String nextNodeStatus = "";
        if (pcbCapacityDataApprove.getFlowType() == 3 || pcbCapacityDataApprove.getFlowType() == 5) {
            if (oldStatus.equals(DB2Config.CapacityDataStatus_FactoryHandle)) {
                //如果是厂家处理，下一状态则是H3C审核
                nextNodeStatus = DB2Config.CapacityDataStatus_H3CAudit;
                nextNodeUserId = approveConfig.getOperator2();
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_CreateFlow)) {
                //如果是创建流程，下一状态则是厂家处理
                nextNodeStatus = DB2Config.CapacityDataStatus_FactoryHandle;
                nextNodeUserId = approveConfig.getOperator();
                nnextNodeUserId = approveConfig.getOperator2();
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_H3CAudit)) {
                //如果是H3C审核，下一状态则是完成
                nextNodeStatus = DB2Config.CapacityDataStatus_Wancheng;
            }
        }
        if (pcbCapacityDataApprove.getFlowType() == 4) {
            if (oldStatus.equals(DB2Config.CapacityDataStatus_CreateFlow)) {
                //如果是创建流程，下一状态则是H3C审核
                nextNodeStatus = DB2Config.CapacityDataStatus_H3CAudit;
                nextNodeUserId = approveConfig.getOperator();
                nnextNodeUserId = approveConfig.getOperator2();
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_H3CAudit)) {
                //如果是H3C审核，下一状态则是厂家确认
                nextNodeStatus = DB2Config.CapacityDataStatus_FactoryConfirm;
                nextNodeUserId = approveConfig.getOperator2();
                nnextNodeUserId = approveConfig.getOperator3();
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_FactoryConfirm)) {
                //如果是厂家确认，下一状态则是H3C审核2
                nextNodeStatus = DB2Config.CapacityDataStatus_H3CAudit2;
                nextNodeUserId = approveConfig.getOperator3();
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_H3CAudit2)) {
                //如果是H3C审核2，下一状态则是完成
                nextNodeStatus = DB2Config.CapacityDataStatus_Wancheng;
            }
        }
        if (pcbCapacityDataApprove.getFlowType() == 2) {
            if (oldStatus.equals(DB2Config.CapacityDataStatus_CreateFlow)) {
                //如果是创建流程，下一状态则是处理人
                nextNodeStatus = DB2Config.CapacityDataStatus_Chuliren;
                nextNodeUserId = approveConfig.getOperator2();
                nnextNodeUserId = approveConfig.getOperator3();
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_Chuliren)) {
                //如果是处理人，下一状态则是H3C终审
                nextNodeStatus = DB2Config.CapacityDataStatus_H3CAudit3;
                nextNodeUserId = approveConfig.getOperator3();
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_H3CAudit3)) {
                //如果是H3C终审，下一状态则是完成
                nextNodeStatus = DB2Config.CapacityDataStatus_Wancheng;
            }
        }

        try {
            //更新审批状态
            pcbCapacityDataApprove.setApproveStatus(nextNodeStatus);
            pcbCapacityDataApprove.setUpdateTime(new Date());
            pcbCapacityDataApprove.setUpdateUser(userId);
            pcbCapacityDataApprove.setApproveUserId(nextNodeUserId == null ? null : nextNodeUserId.toString());
            Integer count = pcbCapacityDataApproveDao.update(pcbCapacityDataApprove);
            if (count > 0) {
                PcbCapacityDataApprove newData = pcbCapacityDataApproveDao.getById(approveDataId);
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批", 2, 1, new Date(), str_oldPcbCapacityApproveDetail, JSONObject.toJSONString(newData)));
            }

            //更新当前节点审批详情
            pcbCapacityApproveDetail.setRemark(remark);
            pcbCapacityApproveDetail.setCopyUserId(copyUserId);
            pcbCapacityApproveDetail.setApproveUserId(Integer.parseInt(userId));
            pcbCapacityApproveDetail.setNextNodeUserId(nextNodeUserId);
            pcbCapacityApproveDetail.setUpdateTime(new Date());
            pcbCapacityApproveDetail.setUpdateUser(userId);
            count = pcbCapacityApproveDetailDao.update(pcbCapacityApproveDetail);
            if (count > 0) {
                PcbCapacityApproveDetail newData = pcbCapacityApproveDetailDao.getById(pcbCapacityApproveDetail.getId());
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批细节", 2, 1, new Date(), str_oldPcbCapacityDataApprove, JSONObject.toJSONString(newData)));
            }
            //处理图片
            if (fileList != null) {
                for (int i = 0; i < fileList.size(); i++) {
                    JSONObject joFile = (JSONObject) fileList.getJSONObject(i);
                    PcbCapacityApproveDetailFile pcbCapacityApproveDetailFile = new PcbCapacityApproveDetailFile();
                    pcbCapacityApproveDetailFile.setFlowType(pcbCapacityDataApprove.getFlowType());
                    pcbCapacityApproveDetailFile.setDataId(pcbCapacityDataApprove.getId());
                    pcbCapacityApproveDetailFile.setDetailDataId(pcbCapacityApproveDetail.getId());
                    pcbCapacityApproveDetailFile.setFileName(joFile.getString("oldName"));
                    pcbCapacityApproveDetailFile.setFileRelatePath(joFile.getString("relatePath"));
                    pcbCapacityApproveDetailFile.setUrl(joFile.getString("url"));
                    pcbCapacityApproveDetailFile.setRemark(joFile.getString("remark"));
                    pcbCapacityApproveDetailFile.setSecretKey(joFile.getString("secretKey"));
                    pcbCapacityApproveDetailFile.setFileSid(joFile.getString("fileSid"));
                    pcbCapacityApproveDetailFile.setCreateTime(new Date());
                    pcbCapacityApproveDetailFile.setCreateUser(userId);
                    count = pcbCapacityApproveDetailFileDao.insert(pcbCapacityApproveDetailFile);
                }
            }

            //添加下一节点审批详情
            if (!StringUtils.isBlank((nextNodeStatus)) && !nextNodeStatus.equals(DB2Config.CapacityDataStatus_Wancheng)) {
                PcbCapacityApproveDetail search = new PcbCapacityApproveDetail();
                search.setFlowType(pcbCapacityDataApprove.getFlowType());
                search.setDataId(pcbCapacityDataApprove.getId());
                search.setApproveNode(nextNodeStatus);
                List<PcbCapacityApproveDetail> byLimit = pcbCapacityApproveDetailDao.getByCondition(search);
                if (byLimit.size() == 0) {
                    PcbCapacityApproveDetail pcbCapacityApproveDetail2 = new PcbCapacityApproveDetail();
                    pcbCapacityApproveDetail2.setFlowType(pcbCapacityDataApprove.getFlowType());
                    pcbCapacityApproveDetail2.setDataId(approveDataId);
                    pcbCapacityApproveDetail2.setApproveNode(nextNodeStatus);
                    pcbCapacityApproveDetail2.setApplyUserId(Integer.parseInt(userId));
                    pcbCapacityApproveDetail2.setApproveUserId(nextNodeUserId);
                    //2025/1/2，author:zyqin
                    pcbCapacityApproveDetail2.setNextNodeUserId(nnextNodeUserId);
                    pcbCapacityApproveDetail2.setDepartmentId(null);
                    pcbCapacityApproveDetail2.setSonFactoryId(pcbCapacityApproveDetail.getSonFactoryId());
                    pcbCapacityApproveDetail2.setFileIds(null);
                    pcbCapacityApproveDetail2.setRemark(null);
                    pcbCapacityApproveDetail2.setCreateTime(new Date());
                    pcbCapacityApproveDetail2.setCreateUser(userId);
                    pcbCapacityApproveDetail2.setStatus(1);
                    pcbCapacityApproveDetail2.setSort(100);
                    count = pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail2);
                    if (count > 0) {
                        PcbCapacityDataApprove newData = pcbCapacityDataApproveDao.getById(approveDataId);
                        operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批细节", 2, 1, new Date(), str_oldPcbCapacityDataApprove, JSONObject.toJSONString(newData)));
                    }
                }


            }

            //添加审批过程记录
            PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
            pcbApproveProcess.setApproveType(pcbCapacityDataApprove.getFlowType());
            pcbApproveProcess.setDataId(pcbCapacityDataApprove.getId());
            pcbApproveProcess.setOldStatus(oldStatus);
            pcbApproveProcess.setNewStatus(nextNodeStatus);
            pcbApproveProcess.setRemark(remark);
            pcbApproveProcess.setApproveNode(userId);
            pcbApproveProcess.setCreateTime(new Date());
            pcbApproveProcessDao.insert(pcbApproveProcess);
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }


    @Transactional(transactionManager = "MysqlTransactionManager2")
    @Override
    public Result backToPreNode(String data) {
        String userId = UserHeaderHolder.getUserId();
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer id = jsonObject.getInteger("id");
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "param id is null", null);
        }
        JSONArray fileList = jsonObject.getJSONArray("fileList");
        Integer copyUserId = jsonObject.getInteger("copyUserId");

        String remark = jsonObject.getString("remark");
        String rowKey = jsonObject.getString("rowKey");
        PcbCapacityApproveDetail pcbCapacityApproveDetail = pcbCapacityApproveDetailDao.getById(id);
        List<PcbCapacityApproveDetail> curDetails = pcbCapacityApproveDetailDao.getByLimit(pcbCapacityApproveDetail.getFlowType(), pcbCapacityApproveDetail.getDataId());
        PcbCapacityApproveDetail preDetail = new PcbCapacityApproveDetail();

        String str_oldPcbCapacityApproveDetail = JSONObject.toJSONString(pcbCapacityApproveDetail);
        String oldStatus = pcbCapacityApproveDetail.getApproveNode();

        int approveDataId = pcbCapacityApproveDetail.getDataId();
        PcbCapacityDataApprove pcbCapacityDataApprove = pcbCapacityDataApproveDao.getById(approveDataId);
        String str_oldPcbCapacityDataApprove = JSONObject.toJSONString(pcbCapacityDataApprove);
        int flowType = pcbCapacityDataApprove.getFlowType();
        String preNodeStatus = "";
        if (flowType == 3 || flowType == 5) {
            if (oldStatus.equals(DB2Config.CapacityDataStatus_FactoryHandle)) {
                //如果当前节点是厂家处理，上一节点则是创建流程
                preDetail = curDetails.stream()
                        .filter(item -> "创建流程".equals(item.getApproveNode()))
                        .findFirst().get();
                preNodeStatus = DB2Config.CapacityDataStatus_CreateFlow;
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_H3CAudit)) {
                //如果当前节点是H3C审核，上一节点则是厂家处理
                preDetail = curDetails.stream()
                        .filter(item -> "厂家处理".equals(item.getApproveNode()))
                        .findFirst().get();
                preNodeStatus = DB2Config.CapacityDataStatus_FactoryHandle;
            }
        }
        if (flowType == 4) {
            if (oldStatus.equals(DB2Config.CapacityDataStatus_H3CAudit)) {
                //如果当前节点是H3C审核，上一节点则是创建流程
                preDetail = curDetails.stream()
                        .filter(item -> "创建流程".equals(item.getApproveNode()))
                        .findFirst().get();
                preNodeStatus = DB2Config.CapacityDataStatus_CreateFlow;
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_FactoryConfirm)) {
                //如果当前节点是厂家确认，上一节点则是H3C审核
                preDetail = curDetails.stream()
                        .filter(item -> "H3C审核".equals(item.getApproveNode()))
                        .findFirst().get();
                preNodeStatus = DB2Config.CapacityDataStatus_H3CAudit;
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_H3CAudit2)) {
                //如果当前节点是H3C审核，上一节点则是厂家确认
                preDetail = curDetails.stream()
                        .filter(item -> "厂家确认".equals(item.getApproveNode()))
                        .findFirst().get();
                preNodeStatus = DB2Config.CapacityDataStatus_FactoryConfirm;
            }
        }
        if (flowType == 2) {
            if (oldStatus.equals(DB2Config.CapacityDataStatus_Chuliren)) {
                //如果当前节点是处理人，上一节点则是创建流程
                preDetail = curDetails.stream()
                        .filter(item -> "创建流程".equals(item.getApproveNode()))
                        .findFirst().get();
                preNodeStatus = DB2Config.CapacityDataStatus_CreateFlow;
            } else if (oldStatus.equals(DB2Config.CapacityDataStatus_H3CAudit3)) {
                //如果当前节点是H3C终审，上一节点则是处理人
                preDetail = curDetails.stream()
                        .filter(item -> "处理人".equals(item.getApproveNode()))
                        .findFirst().get();
                preNodeStatus = DB2Config.CapacityDataStatus_Chuliren;
            }
        }
        //直接退回给上一状态处理人
        Integer nextNodeUserId = 0;
        if("创建流程".equals(preDetail.getApproveNode()))
        {
            nextNodeUserId = preDetail.getApplyUserId();
        }else{
            nextNodeUserId = preDetail.getApproveUserId();
        }
        if(nextNodeUserId == 0)
        {
            return ResultUtil.error(500, "不存在用户id为0", "no user who's id equals zero", null);
        }
        try {
            //更新审批状态
            pcbCapacityDataApprove.setApproveStatus(preNodeStatus);
            pcbCapacityDataApprove.setUpdateTime(new Date());
            pcbCapacityDataApprove.setUpdateUser(userId);
            pcbCapacityDataApprove.setApproveUserId(String.valueOf(nextNodeUserId));
            Integer count = pcbCapacityDataApproveDao.update(pcbCapacityDataApprove);
            if (count > 0) {
                PcbCapacityDataApprove newData = pcbCapacityDataApproveDao.getById(approveDataId);
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批", 2, 1, new Date(), str_oldPcbCapacityApproveDetail, JSONObject.toJSONString(newData)));
            }

            //更新当前节点审批详情
            pcbCapacityApproveDetail.setRemark(remark);
            pcbCapacityApproveDetail.setCopyUserId(copyUserId);
            pcbCapacityApproveDetail.setUpdateTime(new Date());
            pcbCapacityApproveDetail.setUpdateUser(userId);
            count = pcbCapacityApproveDetailDao.update(pcbCapacityApproveDetail);
            if (count > 0) {
                PcbCapacityApproveDetail newData = pcbCapacityApproveDetailDao.getById(pcbCapacityApproveDetail.getId());
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批细节", 2, 1, new Date(), str_oldPcbCapacityDataApprove, JSONObject.toJSONString(newData)));
            }

            //更新前一节点审批详情
            preDetail.setRemark(remark);
            preDetail.setCopyUserId(copyUserId);
            preDetail.setApproveUserId(nextNodeUserId);
            preDetail.setUpdateTime(new Date());
            preDetail.setUpdateUser(userId);
            count = pcbCapacityApproveDetailDao.update(preDetail);
            if (count > 0) {
                PcbCapacityApproveDetail newData = pcbCapacityApproveDetailDao.getById(preDetail.getId());
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批细节", 2, 1, new Date(), str_oldPcbCapacityDataApprove, JSONObject.toJSONString(newData)));
            }
            //处理附件
            if (fileList != null) {
                for (int i = 0; i < fileList.size(); i++) {
                    JSONObject joFile = (JSONObject) fileList.getJSONObject(i);
                    PcbCapacityApproveDetailFile pcbCapacityApproveDetailFile = new PcbCapacityApproveDetailFile();
                    pcbCapacityApproveDetailFile.setFlowType(flowType);
                    pcbCapacityApproveDetailFile.setDataId(pcbCapacityDataApprove.getId());
                    pcbCapacityApproveDetailFile.setDetailDataId(pcbCapacityApproveDetail.getId());
                    pcbCapacityApproveDetailFile.setFileName(joFile.getString("oldName"));
                    pcbCapacityApproveDetailFile.setFileRelatePath(joFile.getString("relatePath"));
                    pcbCapacityApproveDetailFile.setUrl(joFile.getString("url"));
                    pcbCapacityApproveDetailFile.setRemark(joFile.getString("remark"));
                    pcbCapacityApproveDetailFile.setSecretKey(joFile.getString("secretKey"));
                    pcbCapacityApproveDetailFile.setFileSid(joFile.getString("fileSid"));
                    pcbCapacityApproveDetailFile.setCreateTime(new Date());
                    pcbCapacityApproveDetailFile.setCreateUser(userId);
                    count = pcbCapacityApproveDetailFileDao.insert(pcbCapacityApproveDetailFile);
                }
            }

            //添加审批过程记录
            PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
            pcbApproveProcess.setApproveType(flowType);
            pcbApproveProcess.setDataId(pcbCapacityDataApprove.getId());
            pcbApproveProcess.setOldStatus(oldStatus);
            pcbApproveProcess.setNewStatus(preNodeStatus);
            pcbApproveProcess.setRemark(remark);
            pcbApproveProcess.setApproveNode(userId);
            pcbApproveProcess.setCreateTime(new Date());
            pcbApproveProcessDao.insert(pcbApproveProcess);
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }

    }

    @Override
    public Result submitForDocumentation(String data) {
        String userId = UserHeaderHolder.getUserId();
        JSONObject jsonObject = JSONObject.parseObject(data);
        Integer id = jsonObject.getInteger("id");
        if (id == null) {
            return ResultUtil.error(500, "参数id为空", "param id is null", null);
        }
        JSONArray fileList = jsonObject.getJSONArray("fileList");
        Integer copyUserId = jsonObject.getInteger("copyUserId");
        Integer nextNodeUserId = jsonObject.getInteger("nextNodeUserId");
        String remark = jsonObject.getString("remark");
        PcbCapacityApproveDetail pcbCapacityApproveDetail = pcbCapacityApproveDetailDao.getById(id);
        String str_oldPcbCapacityApproveDetail = JSONObject.toJSONString(pcbCapacityApproveDetail);
        String oldStatus = pcbCapacityApproveDetail.getApproveNode();
        int approveDataId = pcbCapacityApproveDetail.getDataId();
        PcbCapacityDataApprove pcbCapacityDataApprove = pcbCapacityDataApproveDao.getById(approveDataId);
        String str_oldPcbCapacityDataApprove = JSONObject.toJSONString(pcbCapacityDataApprove);

        String newStatus = "完成";
        try {
            //更新审批状态
            pcbCapacityDataApprove.setApproveStatus(newStatus);
            pcbCapacityDataApprove.setUpdateTime(new Date());
            pcbCapacityDataApprove.setUpdateUser(userId);
            pcbCapacityDataApprove.setApproveUserId(userId);
            Integer count = pcbCapacityDataApproveDao.update(pcbCapacityDataApprove);
            if (count > 0) {
                PcbCapacityDataApprove newData = pcbCapacityDataApproveDao.getById(approveDataId);
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批", 2, 1, new Date(), str_oldPcbCapacityApproveDetail, JSONObject.toJSONString(newData)));
            }

            //更新当前节点审批详情
            pcbCapacityApproveDetail.setRemark(remark);
            pcbCapacityApproveDetail.setCopyUserId(copyUserId);
            pcbCapacityApproveDetail.setApproveUserId(Integer.parseInt(userId));
            pcbCapacityApproveDetail.setNextNodeUserId(nextNodeUserId);
            pcbCapacityApproveDetail.setUpdateTime(new Date());
            pcbCapacityApproveDetail.setUpdateUser(userId);
            count = pcbCapacityApproveDetailDao.update(pcbCapacityApproveDetail);
            if (count > 0) {
                PcbCapacityApproveDetail newData = pcbCapacityApproveDetailDao.getById(pcbCapacityApproveDetail.getId());
                operateService.addOperate(new Operate(2, Integer.parseInt(userId), "PCB工艺能力数据审批细节", 2, 1, new Date(), str_oldPcbCapacityDataApprove, JSONObject.toJSONString(newData)));
            }
            //处理图片
            if (fileList != null) {
                for (int i = 0; i < fileList.size(); i++) {
                    JSONObject joFile = (JSONObject) fileList.getJSONObject(i);
                    PcbCapacityApproveDetailFile pcbCapacityApproveDetailFile = new PcbCapacityApproveDetailFile();
                    pcbCapacityApproveDetailFile.setFlowType(pcbCapacityDataApprove.getFlowType());
                    pcbCapacityApproveDetailFile.setDataId(pcbCapacityDataApprove.getId());
                    pcbCapacityApproveDetailFile.setDetailDataId(pcbCapacityApproveDetail.getId());
                    pcbCapacityApproveDetailFile.setFileName(joFile.getString("oldName"));
                    pcbCapacityApproveDetailFile.setFileRelatePath(joFile.getString("relatePath"));
                    pcbCapacityApproveDetailFile.setUrl(joFile.getString("url"));
                    pcbCapacityApproveDetailFile.setRemark(joFile.getString("remark"));
                    pcbCapacityApproveDetailFile.setSecretKey(joFile.getString("secretKey"));
                    pcbCapacityApproveDetailFile.setFileSid(joFile.getString("fileSid"));
                    pcbCapacityApproveDetailFile.setCreateTime(new Date());
                    pcbCapacityApproveDetailFile.setCreateUser(userId);
                    count = pcbCapacityApproveDetailFileDao.insert(pcbCapacityApproveDetailFile);
                }
            }

            //添加审批过程记录
            PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
            pcbApproveProcess.setApproveType(pcbCapacityDataApprove.getFlowType());
            pcbApproveProcess.setDataId(pcbCapacityDataApprove.getId());
            pcbApproveProcess.setOldStatus(oldStatus);
            pcbApproveProcess.setNewStatus(newStatus);
            pcbApproveProcess.setRemark(remark);
            pcbApproveProcess.setApproveNode(userId);
            pcbApproveProcess.setCreateTime(new Date());
            pcbApproveProcessDao.insert(pcbApproveProcess);
            return ResultUtil.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result createApproveTask(String data) {

        String userId = UserHeaderHolder.getUserId();
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            Integer flowType = jsonObject.getInteger("flowType");
            JSONArray sonFactoryIds = jsonObject.getJSONArray("sonFactoryIds");
            if (flowType == null) {
                return ResultUtil.error(500, "参数flowType为空", "param flowType is null", null);
            }
            if (flowType != 2) {
                if (sonFactoryIds == null) {
                    return ResultUtil.error(500, "参数sonFactoryIds为空", "param sonFactoryIds is null", null);
                }

                for (int i = 0; i < sonFactoryIds.size(); i++) {
                    Integer facId = (Integer) sonFactoryIds.get(i);
                    PcbApproveConfig approveConfig = pcbApproveConfigDao.getOneByLimit(flowType, null, (Integer) sonFactoryIds.get(i));
                    if (approveConfig == null) {
                        return ResultUtil.error(500, "该流程审核人员未配置", "", null);
                    }
                    if (flowType == 3 || flowType == 5) {
                        List<PcbCapacityDataApprove> twoTypes = pcbCapacityDataApproveDao.getTwoTypes(facId);
                        for (int j = 0; j < twoTypes.size(); j++) {
                            if (!DB2Config.CapacityDataStatus_Wancheng.equals(twoTypes.get(j).getApproveStatus())) {
                                return ResultUtil.error(500, "当前厂家有未处理完的能力数据调查或能力数据修改任务", "", null);
                            } else {
                                twoTypes.get(j).setStatus(2);//将之前的都作废
                                pcbCapacityDataApproveDao.update(twoTypes.get(j));
                            }
                        }
                    } else {
                        PcbCapacityDataApprove search = new PcbCapacityDataApprove();
                        search.setFactoryId((Integer) sonFactoryIds.get(i));
                        search.setFlowType(flowType);
                        search.setStatus(1);
                        List<PcbCapacityDataApprove> byLimit = pcbCapacityDataApproveDao.getByLimit(search);
                        if (byLimit.size() > 0) {
                            for (int j = 0; j < byLimit.size(); j++) {
                                if (!byLimit.get(j).getApproveStatus().equals(DB2Config.CapacityDataStatus_Wancheng)) {
                                    return ResultUtil.error(500, "当前厂家有未处理完成的任务", "", null);
                                } else {
                                    byLimit.get(j).setStatus(2);//将之前的都作废
                                    pcbCapacityDataApproveDao.update(byLimit.get(j));
                                }
                            }
                        }
                    }

                }

                for (int i = 0; i < sonFactoryIds.size(); i++) {
                    Integer factoryId = (Integer) sonFactoryIds.get(i);
                    PcbApproveConfig approveConfig = pcbApproveConfigDao.getOneByLimit(flowType, null, (Integer) sonFactoryIds.get(i));
                    //自动创建流程
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    String currentDate = sdf.format(new Date());
                    PcbCapacityDataApprove byFlowNum = pcbCapacityDataApproveDao.getByFlowNum(currentDate);
                    int currentSeq = 0;
                    String flowNum = "";
                    if (byFlowNum != null) {
                        currentSeq = byFlowNum.getSeq();
                    }
                    currentSeq++;
                    //添加审批记录
                    flowNum = currentDate + String.format("%05d", currentSeq);
                    PcbCapacityDataApprove pcbCapacityDataApprove1 = new PcbCapacityDataApprove();
                    pcbCapacityDataApprove1.setFlowNum(flowNum);
                    pcbCapacityDataApprove1.setSeq(currentSeq);
                    pcbCapacityDataApprove1.setFlowType(flowType);
                    pcbCapacityDataApprove1.setFactoryId(factoryId);
                    pcbCapacityDataApprove1.setApproveStatus(DB2Config.CapacityDataStatus_CreateFlow);
                    pcbCapacityDataApprove1.setCreateTime(new Date());
                    pcbCapacityDataApprove1.setCreateUser(userId);
                    pcbCapacityDataApprove1.setApproveUserId(userId);
                    pcbCapacityDataApprove1.setStatus(1);
                    pcbCapacityDataApproveDao.insert(pcbCapacityDataApprove1);
                    //添加审批详情
                    PcbCapacityApproveDetail pcbCapacityApproveDetail = new PcbCapacityApproveDetail();
                    pcbCapacityApproveDetail.setFlowType(flowType);
                    pcbCapacityApproveDetail.setDataId(pcbCapacityDataApprove1.getId());
                    pcbCapacityApproveDetail.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
                    pcbCapacityApproveDetail.setApplyUserId(Integer.parseInt(userId));
                    pcbCapacityApproveDetail.setDepartmentId(null);
                    pcbCapacityApproveDetail.setSonFactoryId(factoryId);
                    pcbCapacityApproveDetail.setFileIds(null);
                    pcbCapacityApproveDetail.setRemark(null);
                    pcbCapacityApproveDetail.setCreateTime(new Date());
                    pcbCapacityApproveDetail.setApproveUserId(Integer.parseInt(userId));
                    pcbCapacityApproveDetail.setCreateUser(userId);
                    pcbCapacityApproveDetail.setNextNodeUserId(approveConfig.getOperator());
                    pcbCapacityApproveDetail.setStatus(1);
                    pcbCapacityApproveDetail.setSort(100);
                    pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail);
                    //添加审批过程记录
                    PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
                    pcbApproveProcess.setApproveType(flowType);
                    pcbApproveProcess.setDataId(pcbCapacityDataApprove1.getId());
                    pcbApproveProcess.setOldStatus("");
                    pcbApproveProcess.setNewStatus(DB2Config.CapacityDataStatus_CreateFlow);
                    pcbApproveProcess.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
                    pcbApproveProcess.setCreateTime(new Date());
                    pcbApproveProcess.setApproveUserId(Integer.parseInt(userId));
                    pcbApproveProcess.setApplyToId(null);
                    pcbApproveProcessDao.insert(pcbApproveProcess);
                }
            } else {
                PcbApproveConfig approveConfig = pcbApproveConfigDao.getOneByLimit(flowType, null, null);
                if (approveConfig == null) {
                    return ResultUtil.error(500, "该流程审核人员未配置", "", null);
                }
                PcbCapacityDataApprove search = new PcbCapacityDataApprove();
                search.setFlowType(flowType);
                search.setStatus(1);
                List<PcbCapacityDataApprove> byLimit = pcbCapacityDataApproveDao.getByLimit(search);
                if (byLimit.size() > 0) {
                    for (int i = 0; i < byLimit.size(); i++) {
                        if (byLimit.get(i).getApproveStatus().equals(DB2Config.CapacityDataStatus_Wancheng)) {
                            byLimit.get(i).setStatus(2);//将之前的都作废
                            pcbCapacityDataApproveDao.update(byLimit.get(i));
                        } else {
                            return ResultUtil.error(500, "当前流程类型有未处理完成的任务", "", null);
                        }
                    }
                }
                //自动创建流程
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String currentDate = sdf.format(new Date());
                PcbCapacityDataApprove byFlowNum = pcbCapacityDataApproveDao.getByFlowNum(currentDate);
                int currentSeq = 0;
                String flowNum = "";
                if (byFlowNum != null) {
                    currentSeq = byFlowNum.getSeq();
                }
                currentSeq++;
                int factoryId = -1;
                //添加审批记录
                flowNum = currentDate + String.format("%05d", currentSeq);
                PcbCapacityDataApprove pcbCapacityDataApprove1 = new PcbCapacityDataApprove();
                pcbCapacityDataApprove1.setFlowNum(flowNum);
                pcbCapacityDataApprove1.setSeq(currentSeq);
                pcbCapacityDataApprove1.setFlowType(flowType);
                pcbCapacityDataApprove1.setFactoryId(factoryId);
                pcbCapacityDataApprove1.setApproveStatus(DB2Config.CapacityDataStatus_CreateFlow);
                pcbCapacityDataApprove1.setCreateTime(new Date());
                pcbCapacityDataApprove1.setCreateUser(userId);
                pcbCapacityDataApprove1.setApproveUserId(userId);
                pcbCapacityDataApprove1.setStatus(1);
                pcbCapacityDataApproveDao.insert(pcbCapacityDataApprove1);
                //添加审批详情
                PcbCapacityApproveDetail pcbCapacityApproveDetail = new PcbCapacityApproveDetail();
                pcbCapacityApproveDetail.setFlowType(flowType);
                pcbCapacityApproveDetail.setDataId(pcbCapacityDataApprove1.getId());
                pcbCapacityApproveDetail.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
                pcbCapacityApproveDetail.setApplyUserId(Integer.parseInt(userId));
                pcbCapacityApproveDetail.setDepartmentId(null);
                pcbCapacityApproveDetail.setSonFactoryId(null);
                pcbCapacityApproveDetail.setFileIds(null);
                pcbCapacityApproveDetail.setRemark(null);
                pcbCapacityApproveDetail.setCreateTime(new Date());
                pcbCapacityApproveDetail.setCreateUser(userId);
                pcbCapacityApproveDetail.setApproveUserId(Integer.parseInt(userId));
                pcbCapacityApproveDetail.setNextNodeUserId(approveConfig.getOperator2());
                pcbCapacityApproveDetail.setStatus(1);
                pcbCapacityApproveDetail.setSort(100);
                pcbCapacityApproveDetailDao.insert(pcbCapacityApproveDetail);
                //添加审批过程记录
                PcbApproveProcess pcbApproveProcess = new PcbApproveProcess();
                pcbApproveProcess.setApproveType(flowType);
                pcbApproveProcess.setDataId(pcbCapacityDataApprove1.getId());
                pcbApproveProcess.setOldStatus("");
                pcbApproveProcess.setNewStatus(DB2Config.CapacityDataStatus_CreateFlow);
                pcbApproveProcess.setApproveNode(DB2Config.CapacityDataStatus_CreateFlow);
                pcbApproveProcess.setCreateTime(new Date());
                pcbApproveProcess.setApproveUserId(Integer.parseInt(userId));
                pcbApproveProcess.setApplyToId(null);
                pcbApproveProcessDao.insert(pcbApproveProcess);
            }


        } catch (Exception e) {
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
        return ResultUtil.success(null);
    }


}
